package com.sram.controller.common;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import com.sram.dao.UserMapper;
import com.sram.entity.User;
import com.sram.service.UserService;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;



public class realm extends AuthorizingRealm{
	/*@Resource
	private UserService userService;*/
	@Resource
	private UserMapper userMapper;
	/**
	 * 验证角色权限
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		String userName=(String)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo=new SimpleAuthorizationInfo();
		List<User> users=  userMapper.getUserOneByName(userName);
		User user =users.get(0);
		Set<String> set = new HashSet<String>();
		if("admin".equals(userName)){
			set.add("admin");
			//authorizationInfo.setRoles(set);
			authorizationInfo.setStringPermissions(set);
		}else{
			set.add("user");
			authorizationInfo.setStringPermissions(set);
		}
		return authorizationInfo;
	}
	/**
	 * 验证登录身份
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String userName=(String)token.getPrincipal();
		List<User> users=  userMapper.getUserOneByName(userName);
        User user =users.get(0);
		if(user!=null){
			System.out.println("user:"+user.getPassword());
			AuthenticationInfo authcInfo=new SimpleAuthenticationInfo(user.getUserName(),user.getPassword(), this.getName());
			return authcInfo;
		}else{
			return null;				
		}
	}

}
